package com.tsugun.mediaplayer.view.widget

import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.Animation
import android.view.animation.TranslateAnimation
import android.widget.RelativeLayout
import com.tsugun.mediaplayer.presenter.utils.LogHelper.TAG

/**
 * 锁屏布局
 * Created by shize on 2017/8/4.
 */

class LockScreenLayout @JvmOverloads constructor(
        context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
    : RelativeLayout(context, attrs, defStyleAttr), GestureDetector.OnGestureListener {

    private val mGestureDetector: GestureDetector = GestureDetector(context, this) // 手势辅助类
    private var mScreenMoveEventListener: ScreenMoveEventListener? = null // 滑动事件监听
    private var mPosL: Int = 0 // Y轴位置
    private var mPosT: Int = 0 // X轴位置
    private var mPosR: Int = 0 // R轴位置
    private var mPosB: Int = 0 // B轴位置
    private var isOpen: Boolean = false // 是否保持界面开启

    init {
        isOpen = true
    }

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        super.onLayout(changed, l, t, r, b)
        mPosL = l
        mPosT = t
        mPosR = r
        mPosB = b
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        mScreenHeight = MeasureSpec.getSize(heightMeasureSpec)
        mScreenWidth = MeasureSpec.getSize(widthMeasureSpec)
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        if (event.action == MotionEvent.ACTION_UP) {
            checkView()
            setState()
        }
        return mGestureDetector.onTouchEvent(event)
    }

    /**
     * 检测是否解锁
     */
    private fun checkView() {
        isOpen = mPosL <= mScreenWidth / 3
        Log.d(TAG, "onTouchEvent: posL=$mPosL isOpen=$isOpen")
    }

    /**
     * 设置控件开关状态
     */
    private fun setState() {
        if (!isOpen) {
            close()
        } else {
            open()
        }
    }

    /**
     * 关闭
     */
    private fun close() {
        isOpen = false
        doAnimation(mPosL, mScreenWidth)
    }

    /**
     * 不关闭
     */
    private fun open() {
        isOpen = true
        doAnimation(mPosL, 0)
    }

    /**
     * 滑动屏幕

     * @param d 滑动距离
     */
    private fun scroll(d: Int) {
        if (mPosL + d < 0) {
            layout(0, 0, mScreenWidth, mScreenHeight)
        } else {
            layout(mPosL + d, mPosT, mPosR + d, mPosB)
        }
        if (mScreenMoveEventListener != null) {
            mScreenMoveEventListener!!.onScroll(d)
        }
    }

    /**
     * 动画

     * @param nowX    当前X轴的位置
     * *
     * @param targetX 目标X轴的位置
     */
    private fun doAnimation(nowX: Int, targetX: Int) {
        val animation = TranslateAnimation(0f, (targetX - nowX).toFloat(), 0f, 0f)
        // 计算得出还有多少距离需要移动，以保持不管还剩多少距离都能以同意速度移动
        animation.duration = TIME_ANIMATION * Math.abs(targetX - nowX) / mScreenWidth
        // 动画插值器
        animation.interpolator = AccelerateDecelerateInterpolator()
        // 动画播放监听器
        animation.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(animation: Animation) {

            }

            override fun onAnimationEnd(animation: Animation) {
                // 先清除未播放完成的动画
                clearAnimation()
                layout(targetX, 0, targetX + mScreenWidth, mScreenHeight)
                // 设置状态回调
                setCallback()
            }

            override fun onAnimationRepeat(animation: Animation) {

            }
        })
        startAnimation(animation)
    }

    /**
     * 设置状态回调
     */
    private fun setCallback() {
        if (mScreenMoveEventListener == null) {
            return
        }
        if (isOpen) {
            mScreenMoveEventListener!!.onOpen()
        } else {
            mScreenMoveEventListener!!.onClose()
        }
    }

    override fun onDown(e: MotionEvent): Boolean {
        Log.d(TAG, "onDown: ")
        return true
    }

    override fun onShowPress(e: MotionEvent) {
        Log.d(TAG, "onShowPress: ")
    }

    override fun onSingleTapUp(e: MotionEvent): Boolean {
        Log.d(TAG, "onSingleTapUp: ")
        return false
    }

    override fun onScroll(e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float): Boolean {
        val d = (e2.x - e1.x).toInt()
        scroll(d)
        return false
    }

    override fun onLongPress(e: MotionEvent) {
        Log.d(TAG, "onLongPress: ")
    }

    override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
        Log.d(TAG, "onFling: vX=" + velocityX)
        if (velocityX > V_CLOSE && e2.x > e1.x) {
            close()
        }
        return false
    }

    /**
     * 设置滑动时间监听器
     */
    fun setScreenMoveEvent(e: ScreenMoveEventListener) {
        mScreenMoveEventListener = e
    }

    /**
     * 滑动事件监听
     */
    interface ScreenMoveEventListener {
        /**
         * 滑动时

         * @param distance 滑动距离
         */
        fun onScroll(distance: Int)

        /**
         * 判断开启
         */
        fun onOpen()

        /**
         * 判读关闭
         */
        fun onClose()
    }

    companion object {

        private val V_CLOSE = 2000 // 最低解锁手速
        private val TIME_ANIMATION: Long = 300 // 动画时间

        private var mScreenHeight: Int = 0 // 屏幕高度
        private var mScreenWidth: Int = 0 // 屏幕宽度
    }
}
